package com.android.manghe.orderpay.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.cache.ConfigHolder
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.config.events.PaySuccessEvent
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.market.model.CartGoodListRes
import com.android.manghe.member.activity.BuyMemberActivity
import com.android.manghe.mine.activity.AddressListActivity
import com.android.manghe.mine.model.AddressInfo
import com.android.manghe.orderpay.adapter.MarketPayGoodAdapter
import com.android.manghe.orderpay.presenter.PNoPriceMarketOrderPayFromCart
import com.android.manghe.utils.AnalyzeUtil
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.zhuli.activity.WebTextActivity
import com.android.manghe.zhuli.activity.ZhuLiProgressActivity
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.*
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.dialogBuyMember
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.etMark
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.layoutAddAddress
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.layoutAddress
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.layoutHaveAddress
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvAddr
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvAddrName
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvAddrTel
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvPay
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvPriceSmall
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvTotalQtyTip
import kotlinx.android.synthetic.main.activity_order_pay_from_cart_no_price.tvTruePrice
import kotlinx.android.synthetic.main.layout_buy_member_dialog.*
import java.text.DecimalFormat

class NoPriceMarketOrderPayFromCartActivity : MVPActivity<PNoPriceMarketOrderPayFromCart>() {

    private val ReqCode_SelectAddress = 1000

    override fun getLayoutId(): Int {
        return R.layout.activity_order_pay_from_cart_no_price
    }

    override fun initData(savedInstanceState: Bundle?) {
        Bus.observe<PaySuccessEvent>().subscribe {
            Bus.send(RefreshCartEvent())
            finish()
        }.registerInBus(this)

        p.selectedGoodList =
            intent.getSerializableExtra("selectedGoodList") as List<CartGoodListRes.DataBean.CartGoodsBean>

        titleBar.setToolbar("确认订单").setLeftIcon(R.mipmap.icon_back_black)
            .setTitleAndStatusBgColor(R.color.white)
        // 配送地址
        layoutAddress.setOnClickListener {
            //添加地址,切换地址
            open(
                AddressListActivity::class.java,
                hashMapOf<String, Any>("isToSelect" to true),
                ReqCode_SelectAddress
            )
        }
        // 结算按钮
        tvPay.setOnClickListener {
            if (p.currentAddress == null) {
                ToastUtil.showShort(this, "请填写配送地址")
            } else{
                if (p.memberBean.level == 0) {
                    //不是会员
                    dialogBuyMember.visibility = View.VISIBLE
                    val config = ConfigHolder.getConfigInfo(this)
                    if (config != null && config.order_exempt_rule_switch == 1) {
                        titleBar.setRightText("规则") {
                            AnalyzeUtil.clickRule(this, 2)
                            WebTextActivity.showActivity(
                                this,
                                "商品助力规则",
                                ConstantsUrl.domain + ConstantsUrl.ZHULI_RULE
                            )
                        }.setRightFontColor(ContextCompat.getColor(this, R.color.colorFont99))
                    }
                }else {
                    p.toPay(etMark.text.toString().trim())
                }
            }
        }
        layoutBuyMember.setOnClickListener {
            //购买会员
            titleBar.setRightText(""){}
            dialogBuyMember.visibility = View.GONE
            open(BuyMemberActivity::class.java)
        }
        ivCloseRound.setOnClickListener {
            titleBar.setRightText(""){}
            dialogBuyMember.visibility = View.GONE
        }
        p.getMemberInfo()
        p.loadAddressList()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (ReqCode_SelectAddress == requestCode) {
                p.setCurrentAddress(data?.getSerializableExtra("addressInfo") as AddressInfo)
                showAddress(p.currentAddress)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun showGoodListView(memberLevel: Int) {
        try {
            tvPay.text = "结算(${p.selectedGoodList.size})"

            val adapter = MarketPayGoodAdapter(this, p.selectedGoodList)
            goodRecyclerView.layoutManager = AutoHeightLayoutManager(this)
            goodRecyclerView.addItemDecoration(
                RecyclerViewDivider(
                    this,
                    LinearLayoutManager.HORIZONTAL,
                    3,
                    ContextCompat.getColor(this, R.color.backgroundGray)
                )
            )
            goodRecyclerView.adapter = adapter

            var allPrice = 0.0
            var totalQty = 0
            for (good in p.selectedGoodList) {
                allPrice += good.subtotal

                totalQty += good.qty
            }
            tvTotalQtyTip.text = "共${totalQty}件商品"

            if(memberLevel > 0) {
                allPrice *= when (memberLevel) {
                    1 -> {
                        0.98
                    }
                    2 -> {
                        0.97
                    }
                    3 -> {
                        0.96
                    }
                    else->{
                        0.95
                    }
                }
            }

            val format = DecimalFormat("0.00")
            val priceStr = format.format(allPrice)

            tvTruePrice.text = "￥$priceStr" //底部总计
            tvPriceSmall.text = tvTruePrice.text //小计
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun showAddress(addressInfo: AddressInfo?) {
        p.setCurrentAddress(addressInfo)
        if (addressInfo == null) {
            layoutAddAddress.visibility = View.VISIBLE
            layoutHaveAddress.visibility = View.GONE
        } else {
            layoutAddAddress.visibility = View.GONE
            layoutHaveAddress.visibility = View.VISIBLE

            tvAddrName.text = addressInfo.name
            tvAddrTel.text = addressInfo.mobile
            tvAddr.text = addressInfo.area + " " + addressInfo.address
        }
    }

    //生成订单完成，打开订单列表界面和面单进度界面
    fun buildOrderDone(orderSN: String, thumb: String, name: String){
        ZhuLiProgressActivity.showActivity(this, orderSN, 0f, thumb, name)
        finish()
    }
}